
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  
<!-- Mirrored from werkzeug.palletsprojects.com/en/1.0.x/local/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 15 Sep 2020 06:37:09 GMT -->
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Context Locals &#8212; Werkzeug Documentation (1.0.x)</title>
    <link rel="stylesheet" href="../_static/werkzeug.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../../../assets.readthedocs.org/static/css/badge_only.css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script async="async" type="text/javascript" src="../../../../assets.readthedocs.org/static/javascript/readthedocs-doc-embed.js"></script>
    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex/index.html" />
    <link rel="search" title="Search" href="../search/index.html" />
    <link rel="next" title="Middleware" href="../middleware/index.html" />
    <link rel="prev" title="URL Helpers" href="../urls/index.html" />
    <link rel="canonical" href="index.html">
  <script>DOCUMENTATION_OPTIONS.URL_ROOT = '../index.html';</script>
   
  
<!-- RTD Extra Head -->

<!-- 
Always link to the latest version, as canonical.
http://docs.readthedocs.org/en/latest/canonical.html
-->
<link rel="canonical" href="index.html" />

<link rel="stylesheet" href="../../../../assets.readthedocs.org/static/css/readthedocs-doc-embed.css" type="text/css" />

<script type="text/javascript" src="../_static/readthedocs-data.js"></script>

<!-- Add page-specific data, which must exist in the page js, not global -->
<script type="text/javascript">
READTHEDOCS_DATA['page'] = "local"
READTHEDOCS_DATA['source_suffix'] = ".rst"
</script>

<script type="text/javascript" src="../../../../assets.readthedocs.org/static/javascript/readthedocs-analytics.js" async="async"></script>

<!-- end RTD <extrahead> -->
</head><body>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex/index.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex/index.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../middleware/index.html" title="Middleware"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../urls/index.html" title="URL Helpers"
             accesskey="P">previous</a> |</li>
        <li class="nav-item nav-item-0"><a href="../index.html">Werkzeug Documentation (1.0.x)</a> &#187;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-werkzeug.local">
<span id="context-locals"></span><h1>Context Locals<a class="headerlink" href="#module-werkzeug.local" title="Permalink to this headline">¶</a></h1>
<p>Sooner or later you have some things you want to have in every single view
or helper function or whatever.  In PHP the way to go are global
variables.  However, that isn’t possible in WSGI applications without a
major drawback:  As soon as you operate on the global namespace your
application isn’t thread-safe any longer.</p>
<p>The Python standard library has a concept called “thread locals” (or thread-local
data). A thread local is a global object in which you can put stuff in and get back
later in a thread-safe and thread-specific way.  That means that whenever you set
or get a value on a thread local object, the thread local object checks in which
thread you are and retrieves the value corresponding to your thread (if one exists).
So, you won’t accidentally get another thread’s data.</p>
<p>This approach, however, has a few disadvantages.  For example, besides threads,
there are other types of concurrency in Python.  A very popular one
is greenlets.  Also, whether every request gets its own thread is not
guaranteed in WSGI.  It could be that a request is reusing a thread from
a previous request, and hence data is left over in the thread local object.</p>
<p>Werkzeug provides its own implementation of local data storage called <cite>werkzeug.local</cite>.
This approach provides a similar functionality to thread locals but also works with
greenlets.</p>
<p>Here’s a simple example of how one could use werkzeug.local:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">werkzeug.local</span> <span class="k">import</span> <span class="n">Local</span><span class="p">,</span> <span class="n">LocalManager</span>

<span class="n">local</span> <span class="o">=</span> <span class="n">Local</span><span class="p">()</span>
<span class="n">local_manager</span> <span class="o">=</span> <span class="n">LocalManager</span><span class="p">([</span><span class="n">local</span><span class="p">])</span>

<span class="k">def</span> <span class="nf">application</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="n">local</span><span class="o">.</span><span class="n">request</span> <span class="o">=</span> <span class="n">request</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">environ</span><span class="p">)</span>
    <span class="o">...</span>

<span class="n">application</span> <span class="o">=</span> <span class="n">local_manager</span><span class="o">.</span><span class="n">make_middleware</span><span class="p">(</span><span class="n">application</span><span class="p">)</span>
</pre></div>
</div>
<p>This binds the request to <cite>local.request</cite>.  Every other piece of code executed
after this assignment in the same context can safely access local.request and
will get the same request object.  The <cite>make_middleware</cite> method on the local
manager ensures that all references to the local objects are cleared up after
the request.</p>
<p>The same context means the same greenlet (if you’re using greenlets) in
the same thread and same process.</p>
<p>If a request object is not yet set on the local object and you try to
access it, you will get an <cite>AttributeError</cite>.  You can use <cite>getattr</cite> to avoid
that:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_request</span><span class="p">():</span>
    <span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">local</span><span class="p">,</span> <span class="s1">&#39;request&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>This will try to get the request or return <cite>None</cite> if the request is not
(yet?) available.</p>
<p>Note that local objects cannot manage themselves, for that you need a local
manager.  You can pass a local manager multiple locals or add additionals
later by appending them to <cite>manager.locals</cite> and every time the manager
cleans up it will clean up all the data left in the locals for this
context.</p>
<dl class="function">
<dt id="werkzeug.local.release_local">
<code class="descclassname">werkzeug.local.</code><code class="descname">release_local</code><span class="sig-paren">(</span><em>local</em><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.release_local" title="Permalink to this definition">¶</a></dt>
<dd><p>Releases the contents of the local for the current context.
This makes it possible to use locals without a manager.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">loc</span> <span class="o">=</span> <span class="n">Local</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">loc</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="mi">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">release_local</span><span class="p">(</span><span class="n">loc</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">loc</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
<p>With this function one can release <code class="xref py py-class docutils literal notranslate"><span class="pre">Local</span></code> objects as well
as <a class="reference internal" href="#werkzeug.local.LocalStack" title="werkzeug.local.LocalStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">LocalStack</span></code></a> objects.  However it is not possible to
release data held by proxies that way, one always has to retain
a reference to the underlying local object in order to be able
to release it.</p>
<details class="changelog">
<summary>Changelog</summary><div class="versionadded">
<p><span class="versionmodified">New in version 0.6.1.</span></p>
</div>
</details></dd></dl>

<dl class="class">
<dt id="werkzeug.local.LocalManager">
<em class="property">class </em><code class="descclassname">werkzeug.local.</code><code class="descname">LocalManager</code><span class="sig-paren">(</span><em>locals=None</em>, <em>ident_func=None</em><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalManager" title="Permalink to this definition">¶</a></dt>
<dd><p>Local objects cannot manage themselves. For that you need a local
manager.  You can pass a local manager multiple locals or add them later
by appending them to <cite>manager.locals</cite>.  Every time the manager cleans up,
it will clean up all the data left in the locals for this context.</p>
<p>The <cite>ident_func</cite> parameter can be added to override the default ident
function for the wrapped locals.</p>
<details class="changelog">
<summary>Changelog</summary><div class="versionchanged">
<p><span class="versionmodified">Changed in version 0.7: </span><cite>ident_func</cite> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 0.6.1: </span>Instead of a manager the <a class="reference internal" href="#werkzeug.local.release_local" title="werkzeug.local.release_local"><code class="xref py py-func docutils literal notranslate"><span class="pre">release_local()</span></code></a> function can be used
as well.</p>
</div>
</details><dl class="method">
<dt id="werkzeug.local.LocalManager.cleanup">
<code class="descname">cleanup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalManager.cleanup" title="Permalink to this definition">¶</a></dt>
<dd><p>Manually clean up the data in the locals for this context.  Call
this at the end of the request or use <cite>make_middleware()</cite>.</p>
</dd></dl>

<dl class="method">
<dt id="werkzeug.local.LocalManager.get_ident">
<code class="descname">get_ident</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalManager.get_ident" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the context identifier the local objects use internally for
this context.  You cannot override this method to change the behavior
but use it to link other context local objects (such as SQLAlchemy’s
scoped sessions) to the Werkzeug locals.</p>
<details class="changelog">
<summary>Changelog</summary><div class="versionchanged">
<p><span class="versionmodified">Changed in version 0.7: </span>You can pass a different ident function to the local manager that
will then be propagated to all the locals passed to the
constructor.</p>
</div>
</details></dd></dl>

<dl class="method">
<dt id="werkzeug.local.LocalManager.make_middleware">
<code class="descname">make_middleware</code><span class="sig-paren">(</span><em>app</em><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalManager.make_middleware" title="Permalink to this definition">¶</a></dt>
<dd><p>Wrap a WSGI application so that cleaning up happens after
request end.</p>
</dd></dl>

<dl class="method">
<dt id="werkzeug.local.LocalManager.middleware">
<code class="descname">middleware</code><span class="sig-paren">(</span><em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalManager.middleware" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <cite>make_middleware</cite> but for decorating functions.</p>
<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@manager</span><span class="o">.</span><span class="n">middleware</span>
<span class="k">def</span> <span class="nf">application</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The difference to <cite>make_middleware</cite> is that the function passed
will have all the arguments copied from the inner application
(name, docstring, module).</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="werkzeug.local.LocalStack">
<em class="property">class </em><code class="descclassname">werkzeug.local.</code><code class="descname">LocalStack</code><a class="headerlink" href="#werkzeug.local.LocalStack" title="Permalink to this definition">¶</a></dt>
<dd><p>This class works similar to a <code class="xref py py-class docutils literal notranslate"><span class="pre">Local</span></code> but keeps a stack
of objects instead.  This is best explained with an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ls</span> <span class="o">=</span> <span class="n">LocalStack</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ls</span><span class="o">.</span><span class="n">push</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ls</span><span class="o">.</span><span class="n">top</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ls</span><span class="o">.</span><span class="n">push</span><span class="p">(</span><span class="mi">23</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ls</span><span class="o">.</span><span class="n">top</span>
<span class="go">23</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ls</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">23</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ls</span><span class="o">.</span><span class="n">top</span>
<span class="go">42</span>
</pre></div>
</div>
<p>They can be force released by using a <a class="reference internal" href="#werkzeug.local.LocalManager" title="werkzeug.local.LocalManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">LocalManager</span></code></a> or with
the <a class="reference internal" href="#werkzeug.local.release_local" title="werkzeug.local.release_local"><code class="xref py py-func docutils literal notranslate"><span class="pre">release_local()</span></code></a> function but the correct way is to pop the
item from the stack after using.  When the stack is empty it will
no longer be bound to the current context (and as such released).</p>
<p>By calling the stack without arguments it returns a proxy that resolves to
the topmost item on the stack.</p>
<details class="changelog">
<summary>Changelog</summary><div class="versionadded">
<p><span class="versionmodified">New in version 0.6.1.</span></p>
</div>
</details><dl class="method">
<dt id="werkzeug.local.LocalStack.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalStack.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes the topmost item from the stack, will return the
old value or <cite>None</cite> if the stack was already empty.</p>
</dd></dl>

<dl class="method">
<dt id="werkzeug.local.LocalStack.push">
<code class="descname">push</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalStack.push" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a new item to the stack</p>
</dd></dl>

<dl class="attribute">
<dt id="werkzeug.local.LocalStack.top">
<code class="descname">top</code><a class="headerlink" href="#werkzeug.local.LocalStack.top" title="Permalink to this definition">¶</a></dt>
<dd><p>The topmost item on the stack.  If the stack is empty,
<cite>None</cite> is returned.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="werkzeug.local.LocalProxy">
<em class="property">class </em><code class="descclassname">werkzeug.local.</code><code class="descname">LocalProxy</code><span class="sig-paren">(</span><em>local</em>, <em>name=None</em><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalProxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Acts as a proxy for a werkzeug local.  Forwards all operations to
a proxied object.  The only operations not supported for forwarding
are right handed operands and any kind of assignment.</p>
<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">werkzeug.local</span> <span class="k">import</span> <span class="n">Local</span>
<span class="n">l</span> <span class="o">=</span> <span class="n">Local</span><span class="p">()</span>

<span class="c1"># these are proxies</span>
<span class="n">request</span> <span class="o">=</span> <span class="n">l</span><span class="p">(</span><span class="s1">&#39;request&#39;</span><span class="p">)</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">l</span><span class="p">(</span><span class="s1">&#39;user&#39;</span><span class="p">)</span>


<span class="kn">from</span> <span class="nn">werkzeug.local</span> <span class="k">import</span> <span class="n">LocalStack</span>
<span class="n">_response_local</span> <span class="o">=</span> <span class="n">LocalStack</span><span class="p">()</span>

<span class="c1"># this is a proxy</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">_response_local</span><span class="p">()</span>
</pre></div>
</div>
<p>Whenever something is bound to l.user / l.request the proxy objects
will forward all operations.  If no object is bound a <a class="reference external" href="https://docs.python.org/3/library/exceptions.html#RuntimeError" title="(in Python v3.8)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>
will be raised.</p>
<p>To create proxies to <code class="xref py py-class docutils literal notranslate"><span class="pre">Local</span></code> or <a class="reference internal" href="#werkzeug.local.LocalStack" title="werkzeug.local.LocalStack"><code class="xref py py-class docutils literal notranslate"><span class="pre">LocalStack</span></code></a> objects,
call the object as shown above.  If you want to have a proxy to an
object looked up by a function, you can (as of Werkzeug 0.6.1) pass
a function to the <a class="reference internal" href="#werkzeug.local.LocalProxy" title="werkzeug.local.LocalProxy"><code class="xref py py-class docutils literal notranslate"><span class="pre">LocalProxy</span></code></a> constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">session</span> <span class="o">=</span> <span class="n">LocalProxy</span><span class="p">(</span><span class="k">lambda</span><span class="p">:</span> <span class="n">get_current_request</span><span class="p">()</span><span class="o">.</span><span class="n">session</span><span class="p">)</span>
</pre></div>
</div>
<details class="changelog">
<summary>Changelog</summary><div class="versionchanged">
<p><span class="versionmodified">Changed in version 0.6.1: </span>The class can be instantiated with a callable as well now.</p>
</div>
</details><p>Keep in mind that <code class="docutils literal notranslate"><span class="pre">repr()</span></code> is also forwarded, so if you want to find
out if you are dealing with a proxy you can do an <code class="docutils literal notranslate"><span class="pre">isinstance()</span></code> check:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">werkzeug.local</span> <span class="kn">import</span> <span class="n">LocalProxy</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">LocalProxy</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>You can also create proxy objects by hand:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">werkzeug.local</span> <span class="kn">import</span> <span class="n">Local</span><span class="p">,</span> <span class="n">LocalProxy</span>
<span class="n">local</span> <span class="o">=</span> <span class="n">Local</span><span class="p">()</span>
<span class="n">request</span> <span class="o">=</span> <span class="n">LocalProxy</span><span class="p">(</span><span class="n">local</span><span class="p">,</span> <span class="s1">&#39;request&#39;</span><span class="p">)</span>
</pre></div>
</div>
<dl class="method">
<dt id="werkzeug.local.LocalProxy._get_current_object">
<code class="descname">_get_current_object</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#werkzeug.local.LocalProxy._get_current_object" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current object.  This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.</p>
</dd></dl>

</dd></dl>

</div>


          </div>
        </div>
      </div>
  <span id="sidebar-top"></span>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  
    
            <p class="logo"><a href="../index.html">
              <img class="logo" src="../_static/werkzeug.png" alt="Logo"/>
            </a></p>
  
<h3>Navigation</h3>
<ul>
  <li><a href="../index.html">Overview</a>
    <ul>
          <li>Previous: <a href="../urls/index.html" title="previous chapter">URL Helpers</a>
          <li>Next: <a href="../middleware/index.html" title="next chapter">Middleware</a>
    </ul>
  </li>
</ul>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="https://werkzeug.palletsprojects.com/en/1.0.x/search/" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
  
    <div class="footer" role="contentinfo">
        &#169; Copyright 2007 Pallets.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.8.5.
    </div>
    <script>
      if (typeof READTHEDOCS_DATA !== 'undefined') {
        if (!READTHEDOCS_DATA.features) {
          READTHEDOCS_DATA.features = {};
        }
        READTHEDOCS_DATA.features.docsearch_disabled = true;
      }
    </script>

  </body>

<!-- Mirrored from werkzeug.palletsprojects.com/en/1.0.x/local/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 15 Sep 2020 06:37:09 GMT -->
</html>